package top.buluoluo.productservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.buluoluo.commoncore.domain.response.Result;
import top.buluoluo.productservice.dto.request.SpuPageRequest;
import top.buluoluo.productservice.dto.response.*;
import top.buluoluo.productservice.dto.result.PageResult;
import top.buluoluo.productservice.entity.*;
import top.buluoluo.productservice.enums.StatusMethod;
import top.buluoluo.productservice.mapper.*;
import top.buluoluo.productservice.service.ProductService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {
    private final CategoryMapper categoryMapper;
    private final BrandMapper brandMapper;
    private final SpuMapper spuMapper;
    private final SkuMapper skuMapper;
    private final DiscountMapper discountMapper;
    private final MerchantMapper merchantMapper;

    /**
     * 获取所有商品分类
     */
    @Override
    public Result<List<CategoryTreeDTO>> getAllCategories() {
        try {
            // 1. 使用BaseMapper的selectList方法查询所有分类
            List<ProductCategory> categories = categoryMapper.selectList(null);

            // 2. 如果查询结果为空，返回空列表
            if (categories == null || categories.isEmpty()) {
                return Result.success(List.of());
            }

            // 3. 构建树形结构
            List<CategoryTreeDTO> treeList = buildCategoryTree(categories);

            // 4. 按sortOrder排序
            treeList.sort((a, b) -> Long.compare(a.getSortOrder(), b.getSortOrder()));

            // 5. 返回成功结果
            return Result.success(treeList);

        } catch (Exception e) {
            // 错误处理，返回失败结果
            return Result.failed("查询分类失败: " + e.getMessage());
        }
    }

    /**
     * 将平铺的分类列表转换为树形结构
     */
    private List<CategoryTreeDTO> buildCategoryTree(List<ProductCategory> categories) {
        // 先将所有分类转换为DTO，并建立ID到DTO的映射
        Map<Long, CategoryTreeDTO> dtoMap = categories.stream()
                .map(CategoryTreeDTO::convertToTreeDTO)
                .collect(Collectors.toMap(CategoryTreeDTO::getId, dto -> dto));

        // 构建树形结构
        List<CategoryTreeDTO> rootCategories = new ArrayList<>();

        for (CategoryTreeDTO dto : dtoMap.values()) {
            if (dto.isRoot()) {
                // 根节点直接添加到结果列表
                rootCategories.add(dto);
            } else {
                // 非根节点，找到父节点并添加为子节点
                CategoryTreeDTO parent = dtoMap.get(dto.getParentId());
                if (parent != null) {
                    parent.addChild(dto);
                }
                // 如果父节点不存在，说明数据不一致，暂时忽略
            }
        }

        // 对每个节点的子节点按sortOrder排序
        dtoMap.values().forEach(dto -> {
            if (dto.hasChildren()) {
                dto.getChildren().sort((a, b) -> Long.compare(a.getSortOrder(), b.getSortOrder()));
            }
        });

        return rootCategories;
    }

    /**
     * 获取商品分类id关联的品牌及其子分类关联的品牌
     */
    @Override
    public Result<List<BrandDTO>> getBrandsByCategoryId(Long categoryId) {
        try {
            // 1. 验证分类是否存在
            ProductCategory category = categoryMapper.selectById(categoryId);
            if (category == null) {
                return Result.failed("分类不存在");
            }

            // 2. 递归获取所有子分类ID（包括自身）
            List<Long> allCategoryIds = getAllDescendantCategoryIdsStream(categoryId);

            // 3. 查询这些分类关联的所有品牌
            List<BrandDTO> brands = brandMapper.selectBrandsByCategoryIds(allCategoryIds);

            // 4. 去重并返回结果
            List<BrandDTO> distinctBrands = brands.stream()
                    .distinct()
                    .collect(Collectors.toList());

            return Result.success(distinctBrands);

        } catch (Exception e) {
            return Result.failed("查询品牌失败: " + e.getMessage());
        }
    }

    /**
     * 递归获取所有子分类ID（包括自身）,使用Stream流
     */
    private List<Long> getAllDescendantCategoryIdsStream(Long categoryId) {
        List<ProductCategory> allCategories = categoryMapper.selectList(null);

        // 构建父ID到子分类ID列表的映射
        Map<Long, List<Long>> parentToChildIds = allCategories.stream()
                .filter(category -> category.getParentId() != null && category.getParentId() != 0)
                .collect(Collectors.groupingBy(
                        ProductCategory::getParentId,
                        Collectors.mapping(ProductCategory::getId, Collectors.toList())
                ));

        List<Long> result = new ArrayList<>();
        collectDescendantIdsRecursive(categoryId, parentToChildIds, result);
        return result;
    }

    /**
     * 递归所有存在的子分类 ID
     */
    private void collectDescendantIdsRecursive(Long currentId, Map<Long, List<Long>> parentToChildIds, List<Long> result) {
        result.add(currentId);

        List<Long> children = parentToChildIds.get(currentId);
        if (children != null) {
            children.forEach(childId ->
                    collectDescendantIdsRecursive(childId, parentToChildIds, result)
            );
        }
    }

    /**
     * 根据商品种类id，品牌id，分页参数进行分页查询spu表
     */
    @Override
    public Result<PageResult<SpuDTO>> getSpuPage(SpuPageRequest request) {
        try {
            // 1. 参数验证
            if (request.getPageNum() == null || request.getPageNum() < 1) {
                request.setPageNum(1);
            }
            if (request.getPageSize() == null || request.getPageSize() < 1 || request.getPageSize() > 100) {
                request.setPageSize(10);
            }

            // 2. 构建查询条件
            LambdaQueryWrapper<ProductSpu> queryWrapper = new LambdaQueryWrapper<>();

            // 动态添加品牌条件
            if (request.getBrandId() != null) {
                queryWrapper.eq(ProductSpu::getBrandId, request.getBrandId());
            }

            // 动态添加分类条件
            if (request.getCategoryId() != null) {
                queryWrapper.apply("{0} MEMBER OF(category_ids)", request.getCategoryId());
            }


            // 3. 执行分页查询
            Page<ProductSpu> page = new Page<>(request.getPageNum(), request.getPageSize());
            Page<ProductSpu> resultPage = spuMapper.selectPage(page, queryWrapper);
            // 4. 转换为DTO列表
            List<SpuDTO> spuDTOs = resultPage.getRecords().stream()
                    .map(SpuDTO::fromEntity)
                    .collect(Collectors.toList());


            // 6. 构建分页结果
            PageResult<SpuDTO> pageResult = new PageResult<>(
                    request.getPageNum(),
                    request.getPageSize(),
                    (int) resultPage.getTotal(),
                    spuDTOs
            );

            return Result.success(pageResult);

        } catch (Exception e) {
            return Result.failed("查询SPU列表失败: " + e.getMessage());
        }
    }
    /**
     * 根据spuId查询spu表
     */
    @Override
    public Result<SpuDTO> getSpuBySpuId(Long spuId) {
        try {
            // 1. 参数验证
            if (spuId == null || spuId <= 0) {
                return Result.failed("SPU ID不能为空且必须大于0");
            }
            // 2. 构建查询条件
            LambdaQueryWrapper<ProductSpu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductSpu::getId, spuId);
            // 3. 执行查询
            ProductSpu spu = spuMapper.selectOne(queryWrapper);
            if (spu == null)
                return Result.failed("商品信息不存在不存在");
            LambdaQueryWrapper<ProductBrand> queryBrandWrapper = new LambdaQueryWrapper<>();
            queryBrandWrapper.eq(ProductBrand::getId, spu.getBrandId());
            ProductBrand brand = brandMapper.selectOne(queryBrandWrapper);
            if (brand == null)
                return Result.failed("商品对应的品牌不存在");
            LambdaQueryWrapper<Merchant> queryMerchantWrapper = new LambdaQueryWrapper<>();
            queryMerchantWrapper.eq(Merchant::getId, spu.getMerchantId());
            Merchant merchant = merchantMapper.selectOne(queryMerchantWrapper);
            if (merchant == null)
                return Result.failed("商品对应的店铺不存在");
            // 4. 转换为DTO
            SpuDTO spuDTO = SpuDTO.fromEntity(spu);
            spuDTO.setBrandName(brand.getName());
            spuDTO.setMerchantName(merchant.getName());
            return Result.success(spuDTO);
        } catch (Exception e) {
            log.error("根据SPU ID查询SPU失败: spuId={}", spuId, e);
            return Result.failed("查询SPU失败: " + e.getMessage());
        }
    }

    /**
     * 根据spuId查询sku表，以列表形式返回
     */
    @Override
    public Result<List<SkuDTO>> getSkuBySpuId(Long spuId) {
        try {
            // 1. 参数验证
            if (spuId == null || spuId <= 0) {
                return Result.failed("SPU ID不能为空且必须大于0");
            }

            // 2. 构建查询条件
            LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductSku::getSpuId, spuId);
            queryWrapper.eq(ProductSku::getStatus, 1); // 只查询启用的SKU
            // 3. 按价格升序排序
            queryWrapper.orderByAsc(ProductSku::getPrice);
            // 4. 执行查询
            List<ProductSku> skuList = skuMapper.selectList(queryWrapper);

            // 5. 转换为DTO
            List<SkuDTO> skuDTOs = skuList.stream()
                    .map(SkuDTO::fromEntity)
                    .collect(Collectors.toList());

            // 5. 返回结果
            return Result.success(skuDTOs);

        } catch (Exception e) {
            log.error("根据SPU ID查询SKU失败: spuId={}", spuId, e);
            return Result.failed("查询SKU失败: " + e.getMessage());
        }
    }

    /**
     * 根据折supId查询单个sKu表
     */
    @Override
    public Result<SkuDTO> getSkuById(Long skuId) {
        try{
            if (skuId == null )
                return Result.failed("skuId不能为空");
            SkuDTO skuDTO = SkuDTO.fromEntity(skuMapper.selectById(skuId));
            return Result.success(skuDTO);
        } catch (Exception e) {
            return Result.failed("查询SKU失败: " + e.getMessage());
        }
    }

    /**
     * 根据折扣ID查询折扣信息
     */
    @Override
    public Result<DiscountDTO> getDiscountById(Long discountId) {
        try {
            // 1. 使用BaseMapper的selectById方法查询
            ProductDiscount discount = discountMapper.selectById(discountId);

            // 2. 检查是否存在
            if (discount == null) {
                return Result.failed("折扣信息不存在");
            }

            // 3. 转换为DTO
            DiscountDTO discountDTO = DiscountDTO.fromEntity(discount);

            // 4. 返回成功结果
            return Result.success(discountDTO);

        } catch (Exception e) {
            log.error("获取折扣信息失败: {}", e.getMessage(), e);
            return Result.failed("系统错误，请稍后重试" + e.getMessage());
        }
    }

    @Override
    public Result<Boolean> checkDiscountValid(Long discountId) {
        try {
            // 1. 参数验证
            if (discountId == null || discountId <= 0) {
                log.warn("无效的折扣ID: {}", discountId);
                return Result.failed("无效的折扣ID");
            }

            // 2. 查询折扣信息
            ProductDiscount discount = discountMapper.selectById(discountId);

            // 3. 检查折扣是否存在
            if (discount == null) {
                log.warn("折扣不存在: discountId={}", discountId);
                return Result.failed("折扣不存在");
            }

            // 4. 检查折扣状态
            if (discount.getStatus() != StatusMethod.ACTIVE) {
                log.debug("折扣状态无效: discountId={}, status={}", discountId, discount.getStatus());
                return Result.success(false);
            }

            // 5. 检查时间有效性
            Date now = new Date();

            // 检查开始时间
            if (discount.getStartTime() != null && now.before(discount.getStartTime())) {
                log.debug("折扣尚未开始: discountId={}, startTime={}", discountId, discount.getStartTime());
                return Result.success(false);
            }

            // 检查结束时间
            if (discount.getEndTime() != null && now.after(discount.getEndTime())) {
                log.debug("折扣已过期: discountId={}, endTime={}", discountId, discount.getEndTime());
                return Result.success(false);
            }

            // 6. 所有检查通过
            log.debug("折扣有效: discountId={}", discountId);
            return Result.success(true);

        } catch (Exception e) {
            log.error("检查折扣有效性失败: discountId={}, error={}", discountId, e.getMessage(), e);
            return Result.failed("系统错误，请稍后重试"+e.getMessage());
        }
    }
}




